from kNearBase import *
from os import listdir

def img2vector(filename):
    returnVect = zeros((1,1024))
    fr = open(filename)
    for i in range(32):
        lineStr = fr.readline()
        for j in range(32):
            returnVect[0, 32*i + j] = int(lineStr[j])
    return returnVect

def handwritingClassTest():
    hwLabels = []
    trainingFileList = listdir('trainingDigits')
    m = len(trainingFileList)
    trainingMat = zeros((m, 1024))
    for i in range(m):
        fileNameStr = trainingFileList[i]
        fileStr = fileNameStr.split('.')[0]
        classNumStr = int(fileStr.split('_')[0])
        hwLabels.append(classNumStr)
        trainingMat[i, :] = img2vector('trainingDigits/%s' % fileNameStr)
    testFileList = listdir('testDigits')
    errorCount = 0.0
    mTest = len(testFileList)
    for i in range(mTest):
        fileNameStr = testFileList[i]
        fileStr = fileNameStr.split('.')[0]
        classNumStr = int(fileStr.split('_')[0])
        vectorUnderTest = img2vector('testDigits/%s' % fileNameStr)
        classifierResult = classify0(vectorUnderTest, trainingMat, hwLabels, 3)

        if(classifierResult != classNumStr):
            print("file: %s, the classifier came back with: %d, the real answer is: %d"
                  % (fileStr, classifierResult, classNumStr))
            errorCount += 1.0
    print("the total number of error is : %d" % errorCount)
    print("the total error rate is : %.2f%%" % (errorCount*100 / float(mTest)))

def test1():
    testVector = img2vector('testDigits/0_13.txt')
    print(testVector[0, 0:31])
    print(testVector[0, 32:63])

#test1()
handwritingClassTest()
